﻿#pragma once

#include <qobject.h>
#include "ObjAutoInject.h"
#include <qbytearray.h>

#include "LogSaver.h"

class Mapper_MEMSData;
class MEMSDataCodec : public QObject, public ObjAutoInject
{
  Q_OBJECT

public:
  enum DataFlag {
    Head = 0xaa,//头部
    SingleData = 0xcc,//单个数据
    MultiData1 = 0xb1,//组数据1
    MultiData2 = 0xb2,//组数据2
    MultiData3 = 0xb3,//组数据3
    MultiData4 = 0xb4,//组数据4
    MultiData5 = 0xb5,//组数据5
    MultiData6 = 0xb6,//组数据6
  };
  enum DataPackagetype
  {
    Single,
    Multi
  };
private://property
  QByteArray dataBuffer;//数据缓冲区
  int dataPackageSize = 17;//数据包长度，单位：字节
  DataPackagetype dataPackagetype = Multi;
  ushort msgId=0;
  bool receivedState=false;
private://dependency
  Mapper_MEMSData* mapper_MEMSData=Q_NULLPTR;
  LogSaver* logSaver=LogSaver::getLogSaver();
public:
  explicit MEMSDataCodec();
  virtual ~MEMSDataCodec();

signals:
  void signal_sendData(QByteArray data);//发送数据到串口
  void signal_feedbackData(int dataGroupIndex, QByteArray data);//发送拆解后的反馈的数据
  void signal_currentDataPackageype(DataPackagetype dataPackagetype);

public slots:
  void slot_decode(QByteArray data);
  //代码优化，模块化
private:
  void decode();
  bool checkDataPackageHead();
  bool checkDataPackageGroupFlag();
  bool checkDataPackageGroupFlag(int* dataPackageType, int* groupIndex);
  bool checkDataPackageCheckSummation(int dataPackageType);
  void dataBufferDropData(int byteCount);
  void addCheckSummation(QByteArray* instruction);
  short char2ToShort(uchar H8, uchar L8);
  char* shortToChar2(short data, char* data1);
  bool checkCheckSummation(int begin, int end);
  char bitSum(char x, char y);
  //geter and seter
public:
  DataPackagetype getDataPackagetype();
  void setDataPackagetype(DataPackagetype dataPackagetype);
  Mapper_MEMSData* getMapper_MEMSData() const;
  void setMapper_MEMSData(Mapper_MEMSData* mapper_MEMSData);
public:
  virtual void objectAutoInjection(QHash<QString,QObject*>* objMap);
};
